

package org.spring.cloud.pilot.endpoint;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Collections;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.endpoint.AbstractEndpoint;
import org.springframework.boot.context.event.ApplicationPreparedEvent;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.jmx.export.annotation.ManagedAttribute;
import org.springframework.jmx.export.annotation.ManagedOperation;
import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.util.StringUtils;


/**
 * 
		* ClassName: RebootEndpoint <br/>
		* Function: TODO ADD FUNCTION. <br/>
		* Reason: TODO ADD REASON(可选). <br/>
		* date: 2019年10月18日 上午11:58:26 <br/>
		*
		* @author admin
		* @version 
		* @since JDK 1.8
 */
@RefreshScope
@ConfigurationProperties("endpoints.reboot")
@ManagedResource

public class RebootEndpoint extends AbstractEndpoint<Map<String, Object>>
    implements ApplicationListener<ApplicationPreparedEvent> {
    
  private static final Logger LOGGER = LoggerFactory.getLogger(RebootEndpoint.class);


    private ConfigurableApplicationContext context;

    private SpringApplication application;
    private Thread shutdownHook;
    private String[] args;

    private ApplicationPreparedEvent event;

    private ServiceRegistry serviceRegistry;

    private Registration registration;

    public RebootEndpoint(String id) {
        super("reboot", true, false);
    }

    public void registerShutdownHook() {
        if (this.shutdownHook == null) {
            // No shutdown hook registered yet.
            this.shutdownHook = new Thread() {
                @Override
                public void run() {
                    try {
                        LOGGER.info("addShutdownHook");
                        if (isOSWindows()) {
                            LOGGER.info("Windows");

                            System.out.println("Windows");

                            // exeCmd = "cmd.exe /C start startZuulServer.bat";
                            try {
                                Thread.sleep(1000L);
                            } catch (InterruptedException ex) {
                                Thread.currentThread().interrupt();
                            }
                            final Process process = Runtime.getRuntime()
                                .exec(new String[] {"cmd", "/c", "java -jar spring-config-client-0.0.1.jar"});

                            printMessage(process.getInputStream());
                            printMessage(process.getErrorStream());
                            int value = process.waitFor();
                            System.out.println(value);

                        } else {
                            // exeCmd = "/bin/sh -c startWeb.sh";
                            // String command = "find " + source.getRoute() + " -name '" + source.getName();
                            
//                            String shpath = "/usr/local/development/spring-config-client/start.sh";
                            try {
                                Thread.sleep(1000L);
                            } catch (InterruptedException ex) {
                                Thread.currentThread().interrupt();
                            }
                            String shpath = "/usr/local/quickpf/config_client/start.sh";

                            LOGGER.info("linux--"+shpath);

                            Process process = Runtime.getRuntime().exec(shpath);
//                             Process process = Runtime.getRuntime().exec(new String[] {"/bin/sh", "-c", "java -jar spring-config-client-0.0.1.jar"});
                             printMessage(process.getInputStream());
                             printMessage(process.getErrorStream());
                             int value = process.waitFor();
                             LOGGER.info(String.valueOf(value));
                             
                        }
                    } catch (Exception e) {
                        LOGGER.error("sdfdsdf", e);
                        e.printStackTrace();
                    }
                }
            };
            Runtime.getRuntime().addShutdownHook(this.shutdownHook);
        }
    }

    @Override
    public Map<String, Object> invoke() {
        registerShutdownHook();
        context.close();
        return Collections
            .unmodifiableMap(Collections.<String, Object>singletonMap("message", "rebootting down, bye..."));

    }

    private static void printMessage(final InputStream input) {
        new Thread(new Runnable() {
            public void run() {

                Reader reader = new InputStreamReader(input);
                BufferedReader bf = new BufferedReader(reader);
                String line = null;
                try {
                    while ((line = bf.readLine()) != null) {
                        LOGGER.info(line);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public static boolean isOSWindows() {
        String osName = System.getProperty("os.name");
//        StringUtils.isEmpty(str)
        if (StringUtils.isEmpty(osName)) {
            return false;
        }
        return osName.startsWith("Windows");
    }

    @Override
    public void onApplicationEvent(ApplicationPreparedEvent input) {
        this.event = input;
        if (this.context == null) {
            this.context = this.event.getApplicationContext();
            this.args = this.event.getArgs();
            this.application = this.event.getSpringApplication();
            this.serviceRegistry = this.context.getBean(ServiceRegistry.class);
            this.registration = this.context.getBean(Registration.class);

        }
    }

    @ManagedAttribute
    public boolean isRunning() {
        if (this.context != null) {
            return this.context.isRunning();
        }
        return false;
    }

    @ManagedOperation
    public synchronized void pause() {
        if (this.context != null) {
            this.context.stop();
        }
    }

    @ManagedOperation
    public synchronized void resume() {
        if (this.context != null) {
            this.context.start();
        }
    }

}
